package ex01.pyrmont;

import java.io.*;

/*
  HTTP Response = Status-Line
    *(( general-header | response-header | entity-header ) CRLF)
    CRLF
    [ message-body ]
    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/

public class Response {

  private static final int BUFFER_SIZE = 1024;
  Request request;

  /**
   * 对象由socket获取到的outputStream
   */
  OutputStream output;

  public Response(OutputStream output) {
    this.output = output;
  }

  public void setRequest(Request request) {
    this.request = request;
  }

  public void sendStaticResource() throws IOException {
    byte[] bytes = new byte[BUFFER_SIZE];
    FileInputStream fis = null;
    String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
            "Content-type: text/html\r\n" +
            "Content-Length: 23\r\n" +
            "\r\n" +
            "<h1>File Not Found</h1>";
    try {
      File file = new File(HttpServer.WEB_ROOT, request.getUri());
      if (file.exists()) {
        //若文件存在将其写到浏览器
        PrintWriter printWriter = new PrintWriter(output);
        printWriter.println("HTTP/1.1 200 OK");
        printWriter.println("Content-Type:text/html;charset=utf-8");
        printWriter.println("Content-length: " + file.length());
        printWriter.println();
        printWriter.flush();
        //获取文件输入流 将文件缓存到 bytes buffer中，再使用output将输入的文件写回output中
        fis = new FileInputStream(file);
        int ch = fis.read(bytes, 0, BUFFER_SIZE);
        while (ch != -1) {
          output.write(bytes, 0, ch);
          ch = fis.read(bytes, 0, BUFFER_SIZE);
        }
        printWriter.close();
      } else {
        output.write(errorMessage.getBytes());
      }
    } catch (Exception e) {
      System.out.println(e);
      output.write(errorMessage.getBytes());
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
  }

}